package com.demo.gateway.controller;

import com.demo.gateway.utils.JwtTokenProvider;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AuthController {

    private final JwtTokenProvider jwtTokenProvider;
    private final PasswordEncoder passwordEncoder;

    // 构造函数注入
    public AuthController(JwtTokenProvider jwtTokenProvider, PasswordEncoder passwordEncoder) {
        this.jwtTokenProvider = jwtTokenProvider;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 登录接口：验证用户名密码，返回 Token
     */
    @PostMapping("/auth/login")
    public Mono<Map<String, String>> login(@RequestBody LoginRequest loginRequest) {
        // 1. 模拟数据库查询用户（实际项目需替换为真实用户服务调用）
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();

        // 2. 验证密码（实际应从数据库查询加密后的密码进行比对）
        // 这里假设正确密码是 "123456"，加密后与输入密码比对
        boolean passwordValid = passwordEncoder.matches(password, passwordEncoder.encode("123456"));

        if (!passwordValid) {
            return Mono.error(new RuntimeException("用户名或密码错误"));
        }

        // 3. 生成 JWT Token（假设用户角色为 ROLE_USER）
        String token = jwtTokenProvider.generateToken(username, password,"ROLE_USER");

        // 4. 返回 Token
        Map<String, String> response = new HashMap<>();
        response.put("token", token);
        response.put("type", "Bearer");
        return Mono.just(response);
    }

    @GetMapping("/hello")
    public Mono<String> hello() {
        return Mono.just("helloworld");
    }


    // 登录请求参数
    public static class LoginRequest {
        private String username;
        private String password;
        // getter/setter
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
}